﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;

using System.Text;

namespace WHC.OrderWater.Commons
{
    public class OleDbHelper
    {
        private string connectionString = "";
        private const string accessPrefix = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User ID=Admin;Jet OLEDB:Database Password=;";

        public OleDbHelper(string accessFilePath)
        {
            connectionString = string.Format(accessPrefix, accessFilePath);
        }

        /// <summary>
        /// 执行Sql，并返回成功的数量
        /// </summary>
        /// <param name="sqlList"></param>
        /// <returns></returns>
        public int ExecuteNonQuery(List<string> sqlList)
        {
            int count = 0;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;

                foreach (string sql in sqlList)
                {
                    command.CommandText = sql;
                    command.CommandType = CommandType.Text;

                    try
                    {
                        command.ExecuteNonQuery();
                        count++;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        continue;
                    }
                }
            }

            return count;
        }

        /// <summary>
        /// 执行Sql，并返回IDataReader对象。
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public IDataReader ExecuteReader(string sql)
        {
            IDataReader reader = null;
            OleDbConnection connection = new OleDbConnection(connectionString);
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;

            command.CommandText = sql;
            command.CommandType = CommandType.Text;

            try
            {
                reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }

            return reader;
        }

    }
}
